package com.oocl.scan.processor;

import com.oocl.scan.db.ArangoDBConnection;
import com.oocl.scan.handler.Handler;
import com.oocl.scan.handler.MethodRelationHandler;
import com.oocl.scan.model.JavaClassElement;
import com.oocl.scan.store.ComponentStore;
import com.oocl.scan.store.JavaClassStore;
import com.oocl.scan.store.RelationshipStore;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JavaParserProcessor implements Processor {

  private static Logger logger = LoggerFactory.getLogger(JavaParserProcessor.class);
  private ExecutorService threadPool = Executors.newFixedThreadPool(10);

  private List<Handler> handlerList;

  public void process() {
    handlerList = Arrays.asList(new MethodRelationHandler());

    for (Handler handler : handlerList) {
      threadPool.execute(new Runnable() {
        @Override
        public void run() {
          Object[] objects = JavaClassStore.getInstance().getQueue();
          for (Object object : objects) {
            handler.handle((JavaClassElement) object);
          }
        }
      });
    }
    afterHandler();
  }

  private void afterHandler() {
    threadPool.shutdown();

    while (true) {
      if (threadPool.isTerminated()) {
        for (Handler handler : handlerList) {
          handler.shutdown();
        }
        ComponentStore.getInstance().saveComponent();
        RelationshipStore.getInstance().saveRelationship();
        logger.info("====================================== Java Parser Processor Scan Done ======================================");
        break;
      }
    }
    ArangoDBConnection.shutdown();
  }
}
